<template>
  <div class="app-container">
    <el-row>
      <!-- 树结构 -->
      <el-col :span="6" :xs="24">
        <div class="mainbox-left">
          <div class="box-card">
            <!-- 搜索栏 -->
            <el-input
              v-model.trim="filterText"
              prefix-icon="el-icon-search"
              placeholder="请输入组织名称"
              maxlength="30"
              style="margin: 20px 0;"
            />
            <el-tree
              ref="tree"
              :empty-text="$store.getters.dataText"
              :style="{'--lightOpacity':lightTheme}"
              class="left-tree"
              :data="tree"
              :load="load"
              lazy
              :props="defaultProps"
              :default-expand-all="false"
              :expand-on-click-node="false"
              :highlight-current="true"
              :current-node-key="currentKey"
              :filter-node-method="filterNode"
              node-key="id"
              @node-click="handleNodeClick"
            >
              <span slot-scope="{ node}">
                <el-tooltip class="item" effect="dark" :content="node.label" placement="bottom-start">
                  <span class="tree-name">{{ node.label }}</span>
                </el-tooltip>
              </span>
            </el-tree>
          </div>
        </div>
      </el-col>
      <el-col :span="18" :xs="24" style="padding-left: 0px">
        <div class="none2-border3 userlist mainbox">
          <dt-table
            v-loading="loading"
            :table-opts="tableOpts"
            :pagination-data="{
              total:total,
              queryParams:filterForm
            }"
            @pagination="pagination"
            @searchReset="handleReset"
            @searchChange="handleQuery"
          />
        </div>
      </el-col>
    </el-row>
    <dt-userDialog ref="userDialogRef" />
    <setRole ref="setRoleRef" />
  </div>
</template>

<script>
import hrOrganizationApi from '@/framework/api/userCenter/hrOrganization'
import DtUserDialog from '../../userCenter/userManage/components/dt-userDialog'
import sysUserApi from '@/framework/api/userCenter/sysUser'
import setRole from './components/setRole/index.vue'
export default {
  name: 'UserAuthorization',
  dicts: ['sex', 'user_status'],
  components: { DtUserDialog, setRole },
  data() {
    return {
      filterText: '',
      tree: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      currentKey: '',
      // 遮罩层
      loading: false,
      // 总条数
      total: 0,
      // 用户组织机构关联表格数据
      list: [],
      // 查询参数
      filterForm: {
        account: '',
        realName: '',
        orgId: '',
        pageNo: 1,
        pageSize: 10
      },
      tableOpts: {
        rowKey: 'userId',
        tableData: [],
        toolbarBtn: [],
        // 表格第一列
        firstTableCol: {
          select: false,
          width: 55,
          type: 'selection'
        },
        tableCol: [
          {
            prop: 'account',
            label: '账号',
            show: true,
            search: true
          },
          {
            prop: 'realName',
            label: '姓名',
            show: true,
            search: true
          },
          {
            prop: 'sex',
            label: '性别',
            show: true,
            type: 'dict',
            formatter: () => { return this.dict.type.sex }
          },
          {
            prop: 'positionName',
            label: '岗位',
            show: true
          },
          {
            prop: 'statusFlag',
            label: '启用状态',
            show: true,
            type: 'dict',
            formatter: () => { return this.dict.type.user_status }
          }
        ],
        operator: {
          width: 186,
          operatorBtn: [
            {
              'text': '用户详情',
              permission: ['USERAUTHORIZATION_DETAIL_BUTTON'],
              size: 'small',
              click: (row, col, cellValue) => { return this.detailUserInfo(row) }
            },
            {
              'text': '授权',
              permission: ['USERAUTHORIZATION_EMPOWER_BUTTON'],
              size: 'small',
              disabledChange: (row) => { return row.superAdminFlag === 'Y' },
              click: (row, col, cellValue) => { return this.emPower(row) }
            }
          ]
        }
      }
    }
  },
  computed: {
    lightTheme() {
      return this.$store.state.settings.theme + '19'
    }
  },
  watch: {
    filterText(val) {
      hrOrganizationApi.getOrgListTreeNode({ orgId: 0, orgName: val }).then((res) => {
        const data = res.data.map((item, index) => {
          item.orgId = item.id
          item.orgName = item.name
          return item
        })
        this.tree = data
      })
    }
  },
  created() {
    this.initTree()
  },
  methods: {
    // 获取页面列表
    getList() {
      this.loading = true
      this.filterForm.orgId = this.selectedOrg.id
      this.filterForm.containSelf = false
      sysUserApi.fetchPage(this.filterForm).then((res) => {
        this.tableOpts.tableData = res.data.rows
        this.total = res.data.totalRows
        this.loading = false
      })
    },
    // // 表单重置
    // reset() {
    //   this.form = {
    //   }
    //   this.resetForm('queryForm')
    // },
    /** 搜索按钮操作 */
    handleQuery(formModel) {
      this.filterForm = { ...this.filterForm, ...formModel }
      this.filterForm.pageNo = 1
      this.getList()
    },
    /** 重置按钮操作 */
    handleReset() {
      this.filterForm = {
        account: '',
        realName: '',
        statusFlag: '',
        pageNo: 1,
        pageSize: 10
      }
      this.handleQuery()
    },
    detailUserInfo(row) {
      this.$refs.userDialogRef.openDialog(this.selectedOrg, 'detail', row)
    },
    emPower(row) {
      this.$refs.setRoleRef.setRole(row)
    },
    // // 懒加载
    load(tree, resolve) {
      let orgid = ''
      if (!tree.data || tree.data.length === 0) {
        orgid = 0
        return
      } else {
        orgid = tree.data.id
      }
      hrOrganizationApi.getOrgListTreeNode({ orgId: orgid }).then((res) => {
        const data = res.data.map((item, index) => {
          this.selectedOrg = res.data[0]
          this.currentKey = res.data[0].id

          this.$nextTick(() => {
            this.$refs.tree.setCurrentKey(res.data[0].id)
          })
          return item
        })
        resolve(data)
      })
    },
    // loadPopover(tree, resolve) {
    //   let orgid = ''
    //   if (!tree.data || tree.data.length == 0) {
    //     orgid = 0
    //   } else {
    //     orgid = tree.data.id
    //   }
    //   hrOrganizationApi.getOrgListTreeNode({ orgId: orgid }).then((res) => {
    //     const data = res.data
    //     resolve(data)
    //   })
    // },
    // 左侧树结构
    handleNodeClick(data) {
      this.filterForm.orgId = data.id
      this.selectedOrg = data
      this.currentKey = this.selectedOrg.id
      this.handleQuery()
    },
    // 获取左侧组织树
    initTree() {
      const that = this
      hrOrganizationApi.getOrgListTreeNode({ orgId: 0 }).then((res) => {
        that.tree = res.data
        this.selectedOrg = res.data[0]
        this.currentKey = res.data[0].id
        this.getList()
        this.$nextTick(() => {
          this.$refs.tree.setCurrentKey(res.data[0].id)
        })
      })
    },

    filterNode(value, data) {
      if (!value) return true
      return data.name.indexOf(value) !== -1
    },
    pagination() {
      this.getList()
    }

  }
}
</script>
